package codeRandomThoughts.Test279完全平方数;

public class Solution2 {
    public int numSquares(int n) {
        int max = Integer.MAX_VALUE;

        //从0-i构成的完全平方数中选择一些数,使其和为n,最少的选择数量为dp[j]
        int[] dp = new int[n + 1];
        for (int i = 0; i < dp.length; i++) {
            dp[i] = max;
        }

        dp[0] = 0;

        for (int i = 0; i * i <= n; i++) {
            int num = i * i;
            for (int j = num; j <= n; j++) {
                int post = dp[j - num];
                if (post != max) {
                    dp[j] = Math.min(dp[j], num + 1);
                }
            }
        }

        return dp[n] == max ? -1 : dp[n];
    }
}
